from datetime import datetime
from django import template

register = template.Library()
@register.filter('my_greet')
def greet(value,word):
    return value+word
@register.filter
def time_since(value):
    """
    1分钟以内 刚刚
    1小时以内 几分钟之前
    一天以内 几小时之前
    30天以内 几天之前
    具体的时间


    """
    if not isinstance(value,datetime):
        return value

    now = datetime.now()
    timestamp = (now-value).total_seconds()
    if timestamp < 60:
        return '刚刚'
    elif timestamp >= 60 and timestamp < 60*60:
        minutes = int(timestamp/60)
        return "%s分钟前" % minutes
    elif timestamp >= 60*60 and timestamp < 60*60*24:
        hours = int(timestamp/60/60)
        return "%s小时前" % hours
    elif timestamp >= 60*60*24 and timestamp < 60*60*24*30:
        days = int(timestamp/60/60/24)
        return "%s天前" % days
    else:
        return value.strftime("%Y/%m/%d %H:%M:%S")

register.filter('time_since',time_since)